package org.nidy.erp.filter;

import org.nidy.erp.utils.CurrentThreadArgs;
import org.nidy.erp.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //  1、判断是否为登录请求, 如果是放行
        String uri = req.getRequestURI();
        if (uri.contains("/login")) {
            chain.doFilter(request, response);
            return;
        }
        // 2、获取请求头中的token
        String token = req.getHeader("token");
        // 3、判断token是否为空
        if (token == null || token.isEmpty()) {
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        // 4、判断token是否有效
        try {
            // 解析token
            Claims claims = JwtUtils.parseToken(token);
            // 获取用户ID
            Integer empId = Integer.valueOf(claims.get("id").toString());
            // 将用户ID存储到当前线程
            CurrentThreadArgs.setCurrentId(empId);

        } catch (Exception e) {
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        // 5、放行
        chain.doFilter(request, response);
        // 6、清理当前线程
        CurrentThreadArgs.remove();

    }
}
